﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace NetFrameworkExtensions.Enterprise.EL5
{
  public class UnityBootstrapper
  {
    public IUnityContainer ServiceContainer { get; private set; }

    public IServiceManager ServiceManager { get; private set; }
    
    public UnityBootstrapper()
    {
    }

    public void Run()
    {
      var container = CreateServiceContainer();
      ConfigureContainer(container);

      var serviceLocator = new UnityServiceLocator(container);
      var serviceManager = new ServiceLocatorToManagerAdapter(serviceLocator);

      if (RegisterAsGlobalContainer)
      {
        ServiceLocator.SetLocatorProvider(() => serviceLocator);
        NetFrameworkExtensions.Enterprise.ServiceManager.SetServiceManagerProvider(() => serviceManager);
      }

      ServiceManager = serviceManager;
      ServiceContainer = container;
    }

    protected virtual void ConfigureContainer(IUnityContainer unityContainer)
    {
    }

    protected virtual IUnityContainer CreateServiceContainer()
    {
      return new UnityContainer();
    }

    protected virtual bool RegisterAsGlobalContainer
    {
      get
      {
        return true;
      }
    }
  }
}
